<template>
    <div class="customer-detail">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item :to="{ path: '/consulting/customer' }">我的客户</el-breadcrumb-item>
            <el-breadcrumb-item>课程</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="course-container">
            <div class="table-header">
                <div>
                    <el-button :icon="Plus" type="primary" @click="openCourseDialog">办理课程</el-button>
                </div>
            </div>
            <el-table :data="courses" v-loading="loading" style="width: 100%" height="calc(100vh - 250px)"
                empty-text="暂无课程数据">
                <el-table-column type="index" label="序号" width="80" />
                <el-table-column prop="courseName" label="课程名称" show-overflow-tooltip align="center" />
                <el-table-column prop="secondCategoryName" label="课程分类" align="center" />
                <el-table-column prop="discountPrice" label="课程价格" align="center">
                    <template #default="{ row }">
                        {{ row.discountPrice }}元
                    </template>
                </el-table-column>
                <el-table-column prop="totalHour" label="总课时(h)" align="center" />
                <el-table-column prop="teacher" label="授课老师" align="center">
                    <template #default="{ row }">
                        {{ row.teacher || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="redeemCode" label="兑换码" align="center">
                    <template #default="{ row }">
                        <span class="redeem-code" @click="handleCopy(row.redeemCode)">
                            {{ row.redeemCode || '--' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <el-button type="danger" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                :page-sizes="[10, 20, 50]" layout="prev, pager, next" @current-change="handlePageChange"
                @size-change="handleSizeChange" style="margin-top: 15px; text-align: right;" />
        </div>

        <el-dialog v-model="courseDialogVisible" title="办理课程" width="50%">
            <div class="course-dialog">
                <div class="input-group">
                    <el-input v-model="courseForm.courseName" :prefix-icon="Search" placeholder="输入课程名称" clearable
                        class="input-item" />
                    <el-input v-model="courseForm.category" :prefix-icon="Search" placeholder="输入课程分类" clearable
                        class="input-item" />
                </div>

                <el-table :data="filteredCourses" highlight-current-row height="400"
                    style="width: 100%; margin-top: 20px" @current-change="handleDialogSelectionChange"
                    empty-text="没有找到匹配的课程">
                    <el-table-column prop="courseName" label="课程名称" show-overflow-tooltip align="center">
                        <template #default="{ row }">
                            <span :class="{ 'disabled-course': row.disabled }">{{ row.courseName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="secondCategoryName" label="课程分类" align="center" />
                    <el-table-column prop="discountPrice" label="课程价格" align="center">
                        <template #default="{ row }">
                            {{ row.discountPrice }}元
                        </template>
                    </el-table-column>
                    <el-table-column prop="totalHour" label="总课时(h)" align="center" />
                    <el-table-column label="创建时间" align="center">
                        <template #default="scope">
                            {{ formatCreateTime(scope.row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="课程状态" align="center">
                        <template #default="scope">
                            <el-tag :type="courseStatusMap.type(scope.row.status)">
                                {{ courseStatusMap.label(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="dialog-footer">
                    <el-button @click="courseDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitCourse">确认</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import {
    getCourseBaseInfo,
    getStudentCourseList,
    addStudentCourse
} from '../../../api/consultant/user'

const route = useRoute()

const courses = ref([])
const allCourses = ref([])
const loading = ref(false)
const courseDialogVisible = ref(false)
const selectedCourse = ref(null)

const courseForm = ref({
    courseName: '',
    category: ''
})

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const formatCreateTime = (time) => {
    if (!time) return '-';
    const [datePart, timePart] = time.split('T');
    const pureTime = timePart.slice(0, 8);
    return `${datePart} ${pureTime}`;
};

const courseStatusMap = computed(() => ({
    label: (status) => status === 1 ? '上架' : '未上架',
    type: (status) => status === 1 ? 'success' : 'danger'
}));

const handleCopy = async (code) => {
    try {
        await navigator.clipboard.writeText(code);
        ElMessage({
            message: `兑换码 ${code} 已复制到剪贴板`,
            type: 'success',
            duration: 2000
        });
    } catch (error) {
        fallbackCopy(code);
    }
};

const loadStudentCourses = async () => {
    loading.value = true
    try {
        const res = await getStudentCourseList({
            externalUserid: route.query.id,
            pageNum: currentPage.value,
            pageSize: pageSize.value
        })

        if (res.code === 200) {
            courses.value = res.rows || []
            total.value = res.total || 0
        } else {
            ElMessage.error(res.msg || '获取课程列表失败')
            total.value = 0
        }
    } catch (error) {
        console.error('加载课程列表失败:', error)
        ElMessage.error('加载课程列表失败')
        total.value = 0
    } finally {
        loading.value = false
    }
}

const loadBaseCourses = async () => {
    try {
        const res = await getCourseBaseInfo()
        if (res && Array.isArray(res.rows)) {
            allCourses.value = res.rows
        } else {
            allCourses.value = []
            console.error('返回数据格式错误:', res)
        }
    } catch (error) {
        console.error('加载基础课程失败:', error)
        ElMessage.error('加载基础课程失败')
        allCourses.value = []
    }
}

onMounted(async () => {
    await Promise.all([
        loadStudentCourses(),
        loadBaseCourses()
    ])

    if (route.query.openDialog === 'course') {
        openCourseDialog()
    }
})

const filteredCourses = computed(() => {
    const addedCourseNames = courses.value.map(course => course.courseName)
    return allCourses.value.map(course => {
        const isAdded = addedCourseNames.includes(course.courseName)
        return {
            ...course,
            disabled: isAdded
        }
    }).filter(course => {
        const nameMatch = courseForm.value.courseName
            ? (course.courseName || '').toLowerCase().includes(courseForm.value.courseName.toLowerCase())
            : true
        const categoryMatch = courseForm.value.category
            ? (course.secondCategoryName || '').toLowerCase().includes(courseForm.value.category.toLowerCase())
            : true
        return nameMatch && categoryMatch
    })
})

const handleDialogSelectionChange = (val) => {
    if (val && !val.disabled) {
        selectedCourse.value = val
    } else {
        selectedCourse.value = null
    }
}

const openCourseDialog = () => {
    courseDialogVisible.value = true
    courseForm.value = {
        courseName: '',
        category: ''
    }
    selectedCourse.value = null
}

const submitCourse = async () => {
    if (!selectedCourse.value) {
        ElMessage.warning('请选择一门课程')
        return
    }

    try {
        const res = await addStudentCourse({
            externalUserid: route.query.id,
            courseId: selectedCourse.value.id,
        })

        if (res.code === 200) {
            await loadStudentCourses()
            ElMessage.success('课程办理成功')
            courseDialogVisible.value = false
        } else {
            ElMessage.error(res.msg || '办理课程失败')
        }
    } catch (error) {
        console.error('办理课程失败:', error)
        ElMessage.error('办理课程失败')
    }
}

const handlePageChange = (val) => {
    currentPage.value = val
    loadStudentCourses()
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    loadStudentCourses()
}

const fallbackCopy = (text) => {
    const textarea = document.createElement('textarea')
    textarea.value = text
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
    ElMessage({
        message: `兑换码 ${text} 已复制到剪贴板`,
        type: 'success',
        duration: 2000
    })
}
</script>

<style scoped>
.header {
    margin-bottom: 5px;
    padding: 15px 0;
    font-size: 20px;
}

.profile-container {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    align-items: center;
    position: relative;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
}

.avatar-container {
    flex-shrink: 0;
}

.button-container {
    position: absolute;
    top: 20px;
    right: 20px;
    flex-shrink: 0;
}

.info-container {
    flex: 1;
    padding: 0 20px;
    margin-right: 120px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 10px 0;
}

.info-row {
    display: flex;
    margin: 12px 0;
    align-items: center;
}

.info-label {
    width: 100px;
    text-align: right;
    margin-right: 8px;
    color: #606266;
    font-weight: bold;
}

.info-value {
    flex: 1;
    min-width: 150px;
    padding-right: 30px;
}

.status-badge {
    display: inline-block;
    padding: 2px 8px;
    font-size: 12px;
    border-radius: 4px;
    line-height: 1.5;
}

.status-badge.success {
    background: rgba(106, 195, 61, 0.1);
    border: 1px solid #6AC33D;
    color: #6AC33D;
}

.status-badge.danger {
    background: rgba(245, 108, 108, 0.1);
    border: 1px solid #F56C6C;
    color: #F56C6C;
}

.course-dialog {
    padding: 10px 20px;
}

.input-group {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
}

.input-item {
    flex: 1;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}

.course-container {
    background: #fff;
    border-radius: 4px;
}

.disabled-course {
    color: #c0c4cc;
    text-decoration: line-through;
}

.redeem-code {
    cursor: pointer;
}
</style>